﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace DouYinDown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 下载抖音
        /// </summary>
        /// <param name="url"></param>
        public void DownloadVideo(string url)
        {
            var midUrl = getReferUrl(url);
            //  var midUrl1= getReferUrl(midUrl);
            var model = getVidoId(midUrl);
            DownLoad_Video(model.urllst[0], model.desc);

        }
        /// <summary>
        /// 下载快手视频
        /// </summary>
        /// <param name="url"></param>
        private void DownLoadKSVideo(string url)
        {
            // https://www.kuaishou.com/f/XabAZGkcHTHgMPF 
            //第一步访问链接获取跳转地址
            var firstMidUrl = getReferUrl(url);
            var shareToken = url.Replace("https://www.kuaishou.com/f/", "");
            //https://m.gifshow.com/fw/photo/3x6s9iyp7vwtc2s?cc=share_copylink&kpf=PC_WEB&fid=0&area=profilexxnull&utm_campaign=pc_share&shareMethod=token&utm_medium=pc_share&kpn=KUAISHOU_VISION&subBiz=SINGLE_ROW_WEB&ztDid=web_a4e14c3400f8a4369a449ac1cd7e02e6&shareId=17810788500925&shareToken=XabAZGkcHTHgMPF&authorId=3x9xm9gx6bgq36i&shareMode=app&shareObjectId=3x6s9iyp7vwtc2s&utm_source=pc_share302
            var dd = gethtml(firstMidUrl);
            var secendMidUrl = getReferUrl(firstMidUrl);
            var urlPar = secendMidUrl.Split('?');
            //var shareObjectId = urlPar[0].Replace("https://m.gifshow.com/fw/photo/", "");
            Dictionary<string, string> parmDic = new Dictionary<string, string>();
            var parList = urlPar[1].Split('&');
            for (int k = 0; k < parList.Length; k++)
            {
                var item = parList[k].Split('=');
                parmDic.Add(item[0], item[1]);
            }
            var shareId = parmDic["shareId"];
            var shareChannel = parmDic["cc"];
            var shareMethod = parmDic["shareMethod"];
            var kpn = parmDic["kpn"];
            var subBiz = parmDic["subBiz"];
            var shareObjectId = parmDic["shareObjectId"];
            var photoId = shareObjectId;
            string jsonData = string.Format(@"{{""fid"":""0"",""shareToken"":""{0}"",""shareObjectId"":""{1}"",""shareMethod"":""{2}"",""shareId"":""{3}"",""shareChannel"":""{4}"",""kpn"":""{5}"",""subBiz"":""{6}"",""env"":""SHARE_VIEWER_ENV_TX_TRICK"",""h5Domain"":""m.gifshow.com"",""photoId"":""{7}"",""isLongVideo"":false}}"
                                                , shareToken, shareObjectId, shareMethod, shareId, shareChannel, kpn, subBiz, photoId);
            //此地址获取json 文件 json中包含了视频url
            var postUrl = "https://m.gifshow.com/rest/wd/photo/info?kpn=KUAISHOU_VISION&captchaToken=&__NS_sig3=0f1f5b68f71c853935525150140dbecfe308912d4e4e4c4c4342415b";
            //发送请求
            //https://www.kuaishou.com/f/X-5z5mZAVW11W1WD
            //https://www.kuaishou.com/short-video/3xnpa37ny65b7ku?cc=share_copylink&kpf=PC_WEB&fid=0&area=profilexxnull&utm_campaign=pc_share&shareMethod=token&utm_medium=pc_share&kpn=KUAISHOU_VISION&subBiz=SINGLE_ROW_WEB&ztDid=web_722bf519d66e5881d1f5e16e16f65106&shareId=18147356083022&shareToken=X-5z5mZAVW11W1WD&authorId=3xnm868hmevnbgy&shareMode=app&shareObjectId=3xnpa37ny65b7ku&utm_source=pc_share
            var jsonRet = KuaiShouPost(postUrl, jsonData, secendMidUrl);
            JObject obj = JsonConvert.DeserializeObject<JObject>(jsonRet);
            var videUrl = obj["mp4Url"].ToString();
            var name = obj["shareInfo"]["shareTitle"].ToString();
            DownLoad_Video(videUrl, name);

        }

        /// <summary>
        /// 根据分享的短链接 解析视频信息 或者根据https://m.douyin.com/share/video/7337142578367728948解析
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private VideoInfo getVidoId(string midUrl)
        {
            string html = "";//获取页面信息
            if (!string.IsNullOrEmpty(midUrl))
            {
                html = gethtml(midUrl);

                //"video":{"play_addr":{"uri":"v0d00fg10000cqlnj7iljht9lhppd2g0","url_list"
                //string startStr = "video_id=";
                //string endStr = "&ratio=720p&line=0";
                //int startIndex = html.LastIndexOf(startStr);
                //int endIndex = html.LastIndexOf(endStr);
                //string id = html.Substring(startIndex, endIndex - startIndex);
                // 定义要匹配的模式
                string pattern = @"window._ROUTER_DATA =(.*?)</script>";
                // 创建 Regex 对象并进行匹配
                MatchCollection matches = Regex.Matches(html, pattern, RegexOptions.Singleline);
                // 输出匹配到的结果
                string matchContent = "";
                foreach (Match match in matches)
                {
                    matchContent = match.Value;
                }
                matchContent = matchContent.Replace(@"window._ROUTER_DATA =", "").Replace("</script>", "");
                string data = HttpUtility.UrlDecode(matchContent, System.Text.Encoding.UTF8);
                JObject obj = JsonConvert.DeserializeObject<JObject>(data);

                // id = obj["loaderData"]["video_(id)\u002Fpage"]["videoInfoRes"]["item_list"][0]["video"]["play_addr"]["uri"].ToString();
                // string videoUrl = string.Format("https://aweme.snssdk.com/aweme/v1/play/?{0}", id);


                var videoInfoRes = obj["loaderData"]["video_(id)\u002Fpage"]["videoInfoRes"]["item_list"];

                VideoInfo videoInfo = new VideoInfo();
                videoInfo.urllst = new List<string>();
                // videoInfo.urllst.Add(videoUrl);
                videoInfo.desc = obj["loaderData"]["video_(id)\u002Fpage"]["videoInfoRes"]["item_list"][0]["desc"].ToString();
                for (int k = 0; k < videoInfoRes.Count(); k++)
                {
                    videoInfo.desc = videoInfoRes[k]["desc"].ToString();
                    videoInfo.nickName = videoInfoRes[k]["author"]["nickname"].ToString();

                    videoInfo.sec_uid = videoInfoRes[k]["author"]["sec_uid"].ToString();
                    var urlLst = videoInfoRes[k]["video"]["play_addr"]["url_list"];
                    for (int j = 0; j < urlLst.Count(); j++)
                    {
                        videoInfo.urllst.Add(HttpUtility.UrlDecode(urlLst[j].ToString().Replace("playwm", "play"), System.Text.Encoding.UTF8));
                    }
                }
                return videoInfo;
            }
            return null;
        }
        public static void DownLoad_Video(string url, string name)
        {
            string pathUrl = url;
            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;

            //请求网络路径地址
            request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
            request.Timeout = 5000; // 超时时间
                                    //获得请求结果
            request.UserAgent = "ua";
            response = (System.Net.HttpWebResponse)request.GetResponse();
            //文件下载地址
            string path = System.IO.Directory.GetCurrentDirectory() + @"\temp";

            // 如果不存在就创建file文件夹
            if (!Directory.Exists(path))
            {
                if (path != null) Directory.CreateDirectory(path);
            }
            var nam = Regex.Replace(name, @"[^一-龥]", "");
            path = path + "/" + nam + ".mp4";
            Stream stream = response.GetResponseStream();
            //先创建文件
            Stream sos = new System.IO.FileStream(path, System.IO.FileMode.Create);
            byte[] img = new byte[1024];
            int total = stream.Read(img, 0, img.Length);
            while (total > 0)
            {
                //之后再输出内容
                sos.Write(img, 0, total);
                total = stream.Read(img, 0, img.Length);
            }
            stream.Close();
            stream.Dispose();
            sos.Close();
            sos.Dispose();
        }
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name"></param>
        public static void DownLoad_IMG(List<string> urls, string name)
        {

            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;
            for (int k = 0; k < urls.Count; k++)
            {
                //请求网络路径地址
                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(urls[k]);
                request.Timeout = 5000; // 超时时间
                                        //获得请求结果
                request.UserAgent = "ua";
                response = (System.Net.HttpWebResponse)request.GetResponse();
                //文件下载地址
                string path = System.IO.Directory.GetCurrentDirectory() + @"\temp";

                // 如果不存在就创建file文件夹
                if (!Directory.Exists(path))
                {
                    if (path != null) Directory.CreateDirectory(path);
                }
                var nam = Regex.Replace(name, @"[^一-龥]", "");
                path = path + "/" + nam + k + ".jpg";
                Stream stream = response.GetResponseStream();
                //先创建文件
                Stream sos = new System.IO.FileStream(path, System.IO.FileMode.Create);
                byte[] img = new byte[1024];
                int total = stream.Read(img, 0, img.Length);
                while (total > 0)
                {
                    //之后再输出内容
                    sos.Write(img, 0, total);
                    total = stream.Read(img, 0, img.Length);
                }
                stream.Close();
                stream.Dispose();
                sos.Close();
                sos.Dispose();
            }
        }

        /// <summary>
        /// 获取重定向地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string getReferUrl(string url)
        {
            string orgurl = "";

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                // 设置 AllowAutoRedirect 为 false，防止自动重定向
                request.AllowAutoRedirect = false;
                request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/121.0.0.0";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if ((int)response.StatusCode >= 301 && (int)response.StatusCode <= 399)
                    {
                        orgurl = response.Headers["Location"];
                        orgurl = getReferUrl(orgurl);
                        return orgurl;

                    }
                    if ((int)response.StatusCode == 200)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        var responseStr = reader.ReadToEnd();
                        reader.Close();
                        return url;
                    }
                    return "";

                }
            }
            catch (Exception ex)
            {
                return "";
            }

        }
        private string gethtml(string url)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method = "GET";
　 　 　 　 　 　 //request.ContentType = "application/x-www-form-urlencoded";
　 　 　 　 　 　 request.Accept = "*/*";
            request.Timeout = 10000;
            request.AllowAutoRedirect = false;
            request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/121.0.0.0";

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }

        private string KuaiShouPost(string url, string content, string refererUrl = "")
        {
            string result = "";
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            if (refererUrl != "")
            {
                req.Referer = refererUrl;
            }
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36";
            req.Headers.Add("Cookie", "kpf=PC_WEB; clientid=3; did=web_a4e14c3400f8a4369a449ac1cd7e02e6; kpn=KUAISHOU_VISION");
            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    //if (string.IsNullOrEmpty(textBox1.Text) || !textBox1.Text.StartsWith("https"))
        //    //{
        //    //    MessageBox.Show("输入https开头的地址");
        //    //    return;
        //    //}
        //    //var downUrl = string.Format("https://m.douyin.com/share/user/{0}",richTextBox1.Text);// richTextBox1.Text;
        //    //var midUrl = getReferUrl(downUrl);
        //   // var model = getVidoId(downUrl);
        //    //组织访问用户主页 获取列表信息

        //    string hostUrl = string.Format("https://m.douyin.com/web/api/v2/aweme/post/?reflow_source=reflow_page&sec_uid={0}&count=5&max_cursor=0", richTextBox1.Text);

        //    var jsonData = gethtml(hostUrl);
        //    JObject obj = JsonConvert.DeserializeObject<JObject>(jsonData);
        //    var videlst = obj["aweme_list"];
        //    List<VideoInfo> videoLsts = new List<VideoInfo>();
        //    for (int k = 0; k < videlst.Count(); k++)
        //    {
        //        var sharevideo = "https://m.douyin.com/share/video/" + videlst[k]["aweme_id"].ToString();
        //        var curModel = getVidoId(sharevideo);
        //        videoLsts.Add(curModel);
        //    }

        //    Task.Run(() =>
        //    {
        //        for (int j = 0; j < videoLsts.Count; j++)
        //        {
        //            DownLoad_Video(videoLsts[j].urllst[0], videoLsts[j].desc);
        //        }
        //    });

        //    MessageBox.Show("正在下载，不要关闭程序");
        //}

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string path = System.IO.Directory.GetCurrentDirectory() + @"\temp";
            label2.Text = "下载视频保存在" + path + "中";
            label9.Text = "下载视频保存在" + path + "中";

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            // string dd = "https://m.douyin.com/share/video/7337142578367728948";
            if (string.IsNullOrEmpty(richTextBox1.Text))
            {
                MessageBox.Show("请输入视频分享链接");
                return;
            }
            //处理多个分享链接 解析
            //3.33 XMJ:/ c@A.gb 09/11 祖传奥特曼手把件🙄# 创作灵感 # 搞笑 # vlog日常 # 给生活找点乐子 # 在家憋疯系列   https://v.douyin.com/CeiJjVPX3/ 复制此链接，打开Dou音搜索，直接观看视频！
            //8.41 T @y.gO 08 / 26 rEu:/ # jazz # mercy # 虫虫编舞 # luckydance 关注我，一起学跳舞💃🏻  https://v.douyin.com/CeiJjqsRm/ 复制此链接，打开Dou音搜索，直接观看视频！
            //6.12 nda:/ w@s.rE 08/13 😋# mercy 好久不见啦~我们带着新的编舞又来啦~# jazz # 舞蹈教学  https://v.douyin.com/CeiJjVqDo/ 复制此链接，打开Dou音搜索，直接观看视频！
            //
            string startStr = "https://v.douyin.com";
            string endStr = "复制此链接";
            string pattern = @"https://v.douyin.com(.*?)复制此链接";
            // 创建 Regex 对象并进行匹配
            MatchCollection matches = Regex.Matches(richTextBox1.Text, pattern, RegexOptions.Singleline);
            // 输出匹配到的结果
            string matchContent = "";
            List<string> urlLst = new List<string>();
            foreach (Match match in matches)
            {
                matchContent = match.Value;
                urlLst.Add(matchContent.Replace("复制此链接", "").Trim());
            }


            //var urlLst = richTextBox1.Text.Split('\n');
            label6.Text = "开始下载第一个，请耐心等待";
            label6.BackColor = Color.Yellow;
            Task.Run(() =>
            {
                for (int k = 0; k < urlLst.Count; k++)
                {
                    var num = k + 1;
                    label6.Invoke(new Action(() => label6.Text = "正在下载第" + num + "个"));
                    var downUrl = urlLst[k];
                    if (string.IsNullOrEmpty(downUrl) || !downUrl.StartsWith("https"))
                    {

                        continue;
                    }
                    if (downUrl.Contains("douyin"))
                    {
                        DownloadVideo(downUrl);
                    }
                    else if (downUrl.Contains("kuaishou"))
                    {
                        DownLoadKSVideo(downUrl);
                    }

                }
                label6.Invoke(new Action(() => label6.BackColor = Color.Green));
                label6.Invoke(new Action(() => label6.Text = "下载完成"));
            });

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(textBox1.Text))
            //{
            //    MessageBox.Show("主页地址不能为空");
            //    return;
            //}
            //if (!textBox1.Text.StartsWith("https://www.kuaishou.com/profile/"))
            //{
            //    MessageBox.Show("主页地址输入不正确，请重新输入");
            //    return;
            //}
            //var usrId = textBox1.Text.Replace("https://www.kuaishou.com/profile/", "");
            //string jsonData = string.Format(@"{{""operationName"":""visionProfilePhotoList"",""variables"":{{""userId"":""{0}"",""pcursor"":"""",""page"":""profile""}},""query"":""fragment photoContent on PhotoEntity {{\n  __typename\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  commentCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {{\n    url\n    __typename\n  }}\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  riskTagContent\n  riskTagUrl\n}}\n\nfragment recoPhotoFragment on recoPhotoEntity {{\n  __typename\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  commentCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {{\n    url\n    __typename\n  }}\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  riskTagContent\n  riskTagUrl\n}}\n\nfragment feedContent on Feed {{\n  type\n  author {{\n    id\n    name\n    headerUrl\n    following\n    headerUrls {{\n      url\n      __typename\n    }}\n    __typename\n  }}\n  photo {{\n    ...photoContent\n    ...recoPhotoFragment\n    __typename\n  }}\n  canAddComment\n  llsid\n  status\n  currentPcursor\n  tags {{\n    type\n    name\n    __typename\n  }}\n  __typename\n}}\n\nquery visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {{\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {{\n    result\n    llsid\n    webPageArea\n    feeds {{\n      ...feedContent\n      __typename\n    }}\n    hostName\n    pcursor\n    __typename\n  }}\n}}\n""}}", usrId);
            //string url = "https://www.kuaishou.com/graphql";
            //var html = KuaiShouPost(url, jsonData);
            //if (string.IsNullOrEmpty(html))
            //{
            //    MessageBox.Show("没有获取到数据，请确认输入地址是否正确");
            //    return;
            //}
            //JObject obj = JsonConvert.DeserializeObject<JObject>(html);
            //var lst = obj["data"]["visionProfilePhotoList"]["feeds"];
            //if (lst.Count() == 0)
            //{
            //    MessageBox.Show("稍后重试");
            //    return;
            //}
            //List<VideoInfo> videLst = new List<VideoInfo>();
            //for (int k = 0; k < lst.Count(); k++)
            //{
            //    VideoInfo model = new VideoInfo();
            //    model.desc = lst[k]["photo"]["caption"].ToString();
            //    model.downUrl = lst[k]["photo"]["photoUrl"].ToString();
            //    videLst.Add(model);
            //}

            //Task.Run(() =>
            //{
            //    for (int k = 0; k < videLst.Count; k++)
            //    {
            //        var num = k + 1;
            //        label7.Invoke(new Action(() => label7.Text = "正在下载第" + num + "个"));
            //        var downUrl = videLst[k].downUrl;
            //        if (string.IsNullOrEmpty(downUrl) || !downUrl.StartsWith("https"))
            //        {

            //            continue;
            //        }
            //        DownLoad_Video(downUrl, videLst[k].desc);

            //    }
            //    label7.Invoke(new Action(() => label7.BackColor = Color.Green));
            //    label7.Invoke(new Action(() => label7.Text = "下载完成"));
            //});
        }

        private void xhs_btn_Click(object sender, EventArgs e)
        {
            var url = xhsrichtxb.Text;
            List<string> urlLst = new List<string>();

            string reg = "";
            MatchCollection matches = Regex.Matches(url, reg, RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                urlLst.Add(match.Value);
            } 
            Task.Run(() =>
            {
                for (int k = 0; k < urlLst.Count; k++)
                {
                    var info = GetInfoByurl(urlLst[k]);
                    var num = k + 1;
                    label5.Invoke(new Action(() => label5.Text = "正在下载第" + num + "个"));
                    var downUrl = urlLst[k];
                    if (string.IsNullOrEmpty(downUrl) || !downUrl.StartsWith("http"))
                    {

                        continue;
                    }
                    if (!string.IsNullOrEmpty(info.downUrl))
                    { DownLoad_Video(info.downUrl, info.desc); }
                    else
                    {
                        DownLoad_IMG(info.urllst, info.desc);
                    }
                }
                label5.Invoke(new Action(() => label5.BackColor = Color.Green));
                label5.Invoke(new Action(() => label5.Text = "下载完成"));
            });

        }


        private VideoInfo GetInfoByurl(string url)
        {
            var html = gethtml(url);

            //定义正则 获取视频key 视频描述
            string reg = "(.*?)";
            MatchCollection matches = Regex.Matches(html, reg, RegexOptions.Singleline);
            // 输出匹配到的结果
            //https://www.xiaohongshu.com/explore/67415eb20000000002028caf?xsec_token=AB5Y6ZRjCTdxdr4Dkj3uDuprxq1u3wNkXcyARERXMo4cg=&xsec_source=pc_feed
            //
            string matchContent = "";
            foreach (Match match in matches)
            {
                matchContent = match.Value;
            }
            string jsonData = matchContent;

            var model = GetVideoInfo(jsonData);
            return model;
        }
        /// <summary>
        /// 根据获取的json解析出视频相关信息 url 名称 等
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        private VideoInfo GetVideoInfo(string jsonData)
        {
            VideoInfo videoInfo = new VideoInfo();
            JObject obj = JsonConvert.DeserializeObject<JObject>(jsonData);
            var noteData = obj["LAUNCHER_SSR_STORE_PAGE_DATA"]["noteData"];
            //用户名 用户id
            videoInfo.nickName = noteData["user"]["nickName"].ToString();
            videoInfo.sec_uid = noteData["user"]["userId"].ToString();
            if (noteData["type"].ToString() == "video")
            {
                videoInfo.desc = noteData["desc"].ToString();
                videoInfo.downUrl =   noteData[""][""][""].ToString().Replace("", "/");
            }
            else
            {
                //图片
                JArray array = JArray.Parse(noteData["imageList"].ToString());
                videoInfo.desc = noteData["title"].ToString();
                videoInfo.urllst = new List<string>();
                for (int k = 0; k < array.Count; k++)
                {
                    videoInfo.urllst.Add(JObject.Parse(array[k].ToString())["url"].ToString().Replace("\u002F", "/"));
                }
            }
            return videoInfo;
        }
    }
}
